//
//  MOLYPicAVPlayerCollectionViewCell.m
//  WCImApp
//
//  Created by macMini on 2019/10/22.
//  Copyright © 2019 WCImApp. All rights reserved.
//

#import "MOLYPicAVPlayerCollectionViewCell.h"
#import "QAChooseToSendVC.h"
#import "QAChatViewController.h"
#import "QALookPhotoVC.h"
#import "GGProgressView.h"
#import "DGActivityIndicatorView.h"
#import "ICFileTool.h"
#import <AVFoundation/AVAudioSession.h>
#import <AVFoundation/AVPlayer.h>
#import <AVFoundation/AVAsset.h>
#import "ICMediaManager.h"
#import "ICVideoManager.h"
#import "QAHTTPManager.h"
#import "QAIMDatabase.h"

@interface MOLYPicAVPlayerCollectionViewCell ()<UIGestureRecognizerDelegate>

@property (nonatomic, strong) UIPanGestureRecognizer *pan;
@property (nonatomic, strong) UIButton *playButton;
@property (nonatomic, strong) UILongPressGestureRecognizer *longPress;

@property (nonatomic, strong) UIImageView *loadView;
@property (nonatomic, assign) BOOL isPan;
/**
 暂停、播放、进度条等
 */
@property (nonatomic, strong) UISlider *slider;
@property (nonatomic, strong) UILabel *totalLabel;
@property (nonatomic, strong) UILabel *playingTimeLabel;
/// 无链接时
@property(nonatomic, strong) UIButton *illImgBtn;
@property (nonatomic, assign) CGFloat currentPlayTime;
@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, assign) BOOL isSlider;
@property (nonatomic, assign) BOOL isDownload;
@property (nonatomic, assign) BOOL otherPlay;

@end
@implementation MOLYPicAVPlayerCollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor blackColor];

        // 循环播放
    
        [self addSubview:self.pauseView];
        [self.pauseView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(10);
            make.right.mas_equalTo(-60);
            make.height.mas_equalTo(35);
            make.bottom.mas_equalTo(-30);
        }];
        [self addSubview:self.illImgBtn];
        [self.illImgBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(0);
            make.right.mas_offset(-50);
            make.top.bottom.mas_offset(0);
        }];
        
        if(QATool.isBusy){
            WCIToast.showMsg(@"通话中，请稍后再试");
        }
        
        WeakSelf(ws);
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
        tap.delegate = self;
        [self addGestureRecognizer:tap];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(playerItemDidPlayToEndTimeNotification:)
                                                     name:AVPlayerItemDidPlayToEndTimeNotification
                                                   object:nil];
      
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(recallMsg:)
                                                     name:@"recallMsg"
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti_bothRecallMsg:) name:@"noti_bothRecallMsg" object:nil];

    }
    return self;
}

- (void)tapAction{
    if (self.loadView.hidden == NO) {
        NSLog(@"hhhhhh ai  %d",self.loadView.hidden);
        if (self.dismissBlock) {
            self.dismissBlock();
        }
    } else {
        self.currentPlayTime = 0;
        self.pauseView.hidden = NO;
        self.closeButton.hidden = NO;
        self.pauseButton.hidden = NO;
        self.slider.hidden = NO;
        self.totalLabel.hidden = NO;
        self.playingTimeLabel.hidden = NO;
        [self bringSubviewToFront:self.playButton];
        [self bringSubviewToFront:self.closeButton];
        [self bringSubviewToFront:self.pauseView];
        [self bringSubviewToFront:self.illImgBtn];
    }
}

- (void)addPlayerURL:(NSURL *)URL andOriPath:(NSString *)orgUrl{
    [self releasePlayer];
    self.fileUrl = URL;
    //设置player的参数
    if ([ICFileTool fileExistsAtPath:[URL path]]) {
        [self configPlayerWithUrl:URL];
    }
    [self setUpVideoView];
    if (orgUrl.length == 0) {
        self.illImgBtn.hidden = NO;
        [self bringSubviewToFront:self.illImgBtn];
    }else{
        self.illImgBtn.hidden = YES;
    }
}
/**
 播放状态监听
 */
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    WeakSelf(ws);
    AVPlayerItem *item = object;
    //判断监听对象的状态
    if ([keyPath isEqualToString:@"status"]) {
        if (item.status == AVPlayerItemStatusReadyToPlay) {
            if (!self.isDownload) {
                [self startLoadAnimating];
                self.loadView.hidden = YES;
                [self.loadView removeFromSuperview];
            }
            @try {
               [self.currentItem removeObserver:self forKeyPath:@"status"];
            }
            @catch(NSException *exception) {
                NSLog(@"--%@", exception);
            }
        }
        if(item.status == AVPlayerItemStatusFailed){//有错误的
            NSLog(@"AVPlayerItemStatusFailed");
            self.loadView.hidden = NO;
            [self startLoadAnimating];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    weakSelf.isDirectVideo = NO;
                    @try {
                       [weakSelf.currentItem removeObserver:weakSelf forKeyPath:@"status"];
                    }
                    @catch(NSException *exception) {
                        NSLog(@"--%@", exception);
                    }
                    [weakSelf configPlayerWithUrl:weakSelf.fileUrl];
                    [weakSelf setUpVideoView];
            });
        }
    }
}

- (void)configPlayerWithUrl:(NSURL *)URL {
    [self releasePlayer];
    
    self.currentItem = [AVPlayerItem playerItemWithURL:URL];
    self.isDownload = NO;
    //创建监听（这是一种KOV的监听模式）
    
    [self.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    self.videoView = [[MOVideoLayer alloc]initWithFrame:CGRectZero];
    self.videoView.tag = 10002;
    for (UIView *v in self.subviews) {
        if (v.tag == 10002) {
            [v removeFromSuperview];
        }
    }
    self.videoView.backgroundColor = [UIColor blackColor];
    [self addSubview:self.videoView];
    [self.videoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(0);
        make.left.mas_offset(0);
        make.bottom.mas_offset(0);
        make.right.mas_offset(-50);
    }];
    [self sendSubviewToBack:self.videoView];
    self.player = [AVPlayer playerWithPlayerItem:self.currentItem];
    //AVPlayerLayer
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    [self.videoView.layer addSublayer:self.playerLayer];
    self.videoView.moPlayerLayer = self.playerLayer;
    if (self.isDirectVideo) {
        if(QATool.isBusy){
            [self.player pause];
            self.pauseView.hidden = YES;
            self.closeButton.hidden = YES;
            self.playButton.hidden = NO;
            self.pauseButton.hidden = NO;
            self.pauseButton.selected = NO;
            self.slider.hidden = NO;
            self.totalLabel.hidden = NO;
            self.playingTimeLabel.hidden = NO;
            [self.pauseButton setImage:[UIImage imageNamed:@"video_icon_play"] forState:UIControlStateNormal];
            [self bringSubviewToFront:self.playButton];
            [self bringSubviewToFront:self.closeButton];
            [self bringSubviewToFront:self.pauseView];
        }else{
            [self playVideo];
            self.playButton.hidden = YES;
            self.pauseView.hidden = YES;
            self.closeButton.hidden = YES;
            self.pauseButton.hidden = NO;
            self.pauseButton.selected = YES;
            self.slider.hidden = NO;
            self.totalLabel.hidden = NO;
            self.playingTimeLabel.hidden = NO;
            [self.pauseButton setImage:[UIImage imageNamed:@"video_icon_suspend"] forState:UIControlStateNormal];
            [self bringSubviewToFront:self.playButton];
            [self bringSubviewToFront:self.closeButton];
            [self bringSubviewToFront:self.pauseView];
        }
    }else{
        [self.player pause];
        self.pauseView.hidden = YES;
        self.closeButton.hidden = YES;
        self.playButton.hidden = NO;
        self.pauseButton.hidden = NO;
        self.pauseButton.selected = NO;
        self.slider.hidden = NO;
        self.totalLabel.hidden = NO;
        self.playingTimeLabel.hidden = NO;
        [self.pauseButton setImage:[UIImage imageNamed:@"video_icon_play"] forState:UIControlStateNormal];
        [self bringSubviewToFront:self.playButton];
        [self bringSubviewToFront:self.closeButton];
        [self bringSubviewToFront:self.pauseView];
    }
    self.isSlider = NO;
    self.loadView.hidden = YES;
    // 增加下面这行可以解决iOS10兼容性问题了
    if (@available(iOS 10.0, *)) {
        self.player.automaticallyWaitsToMinimizeStalling = NO;
    }
}

- (void)setUpVideoView {
    
    WeakSelf(ws);

    if (![ICFileTool fileExistsAtPath:[self.fileUrl path]]) {
        //如果本地没有这个视频地址
        _previewImageV = [UIImageView new];
        _previewImageV.userInteractionEnabled = YES;
        _previewImageV.contentMode = UIViewContentModeScaleAspectFit;
        _previewImageV.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleHeight;
        _previewImageV.clipsToBounds = YES;
        _previewImageV.tag = 100001;
        
        NSDictionary *dicMsg;
        if (self.messageFrame) {
            dicMsg = [NSDictionary dictionaryWithJsonString: self.messageFrame.message.receiveMsg];
        } else if (self.videoInfo) {
            dicMsg = [NSDictionary dictionaryWithJsonString:[_videoInfo objectForKey:@"content"]];
            if ([self.videoInfo.allKeys containsObject:@"receiveMsg"]) {
                dicMsg = [NSDictionary dictionaryWithJsonString:[_videoInfo objectForKey:@"receiveMsg"]];
            } else if ([self.videoInfo.allKeys containsObject:@"videoPath"]) {
                dicMsg = self.videoInfo;
            }
        }
        if ([dicMsg.allKeys containsObject:@"localSnapshot"]) {
            NSString *name = [[[dicMsg objectForKey:@"localSnapshot"] lastPathComponent] stringByDeletingPathExtension];
            UIImage *videoArrowImage = [[ICMediaManager sharedManager] videoImageWithFileName:[NSString stringWithFormat:@"%@.jpg",name]];//取图片
            [self.previewImageV setImage:videoArrowImage];
        } else if ([dicMsg.allKeys containsObject:@"snapshot"]) {
            NSString *urlPath = [dicMsg objectForKey:@"videoPath"];
            NSString *path = [[ICVideoManager shareManager] receiveVideoPathWithFileKey:[urlPath.lastPathComponent stringByDeletingPathExtension]];
            UIImage *videoArrowImage = [[ICMediaManager sharedManager] videoConverPhotoWithVideoPath:path
                                                                                                size:self.messageFrame.style.picViewF.size
                                                                                            snapShot:[dicMsg objectForKey:@"snapshot"]
                                                                                            isSender:self.messageFrame.someExtData.isSender];
            [self.previewImageV sd_setImageWithURL:[NSURL URLWithString:[dicMsg objectForKey:@"snapshot"]] placeholderImage:videoArrowImage];
        } else if (self.albumModel) {
            if (self.albumModel.localCover) {
                UIImage *img = [UIImage imageWithData:self.albumModel.localCover];
                [self.previewImageV setImage:img];
            } else {
                [self.previewImageV sd_setImageWithURL:[NSURL URLWithString:self.albumModel.cover_src]];
            }
        }
        self.previewImageV.hidden = NO;
        for (UIView *v in self.subviews) {
            if (v.tag == 100001) {
                [v removeFromSuperview];
            }
        }
        [self addSubview:self.previewImageV];
        [self.previewImageV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.bottom.mas_equalTo(0);
            make.right.mas_equalTo(-50);
        }];
        [self bringSubviewToFront:self.previewImageV];
        [self bringSubviewToFront:self.illImgBtn];
        NSString *fileKey = [dicMsg objectForKey:@"videoPath"];
        if (self.albumModel) {
            fileKey = self.albumModel.src;
        }
        NSString *name = [[fileKey lastPathComponent] stringByDeletingPathExtension];
        NSString *fileLocalPath = [[ICVideoManager shareManager] receiveVideoPathWithFileKey:name];

        self.isDownload = YES;
        self.loadView.hidden = NO;
        [self startLoadAnimating];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSURL *url = [NSURL URLWithString:fileKey];
            // 创建请求对象
            NSURLRequest *request = [NSURLRequest requestWithURL:url];
            //    self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
            
            // 下载文件
            
            weakSelf.task = [QAHTTPManager.manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
                NSLog(@"down progress = %@",downloadProgress);
                
            } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

                // 返回一个URL存储文件
                NSURL *url = [NSURL fileURLWithPath:fileLocalPath];
                
                return url;
            } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (!error) {
                        [weakSelf startLoadAnimating];
                        weakSelf.loadView.hidden = YES;
                        [weakSelf.loadView removeFromSuperview];
                        self.isDownload = NO;
                        //设置展示播放页面位置
                        [weakSelf configPlayerWithUrl:[NSURL fileURLWithPath:fileLocalPath]];
                        [weakSelf setUpVideoView];
                    }
                });

            }];
            
            // 开始下载任务
            [weakSelf.task resume];
        });

    } else {
        
        
        //如果本地存在这个视频地址
       //   self.backgroundColor = [UIColor colorWithPatternImage:self.previewImageV.image];
       if (self.previewImageV) {
           NSLog(@"self.previewImageV removeFromSuperview");
           dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
               [weakSelf.previewImageV removeFromSuperview];
           });
       }
        
        
        NSDictionary *dicMsg;
        NSString *fileKey;
        if (self.messageFrame) {
            dicMsg = [NSDictionary dictionaryWithJsonString: self.messageFrame.message.receiveMsg];
            fileKey = self.messageFrame.message.fileKey;
        } else if (self.videoInfo) {
            if ([self.videoInfo.allKeys containsObject:@"videoPath"]) {
                dicMsg = self.videoInfo;
            } else {
                dicMsg = [NSDictionary dictionaryWithJsonString:[_videoInfo objectForKey:@"content"]];
                fileKey = [_videoInfo objectForKey:@"fileKey"];
                if ([self.videoInfo.allKeys containsObject:@"receiveMsg"]) {
                    dicMsg = [NSDictionary dictionaryWithJsonString:[_videoInfo objectForKey:@"receiveMsg"]];
                }
            }
        }
        
        NSString *name;
        UIImage *videoImage;
        if ([dicMsg.allKeys containsObject:@"localSnapshot"]) {
            name = [[[dicMsg objectForKey:@"localSnapshot"] lastPathComponent] stringByDeletingPathExtension];
            videoImage = [[ICMediaManager sharedManager] videoImageWithFileName:[NSString stringWithFormat:@"%@.jpg",name]];//取图片
        } else {
            name = [[fileKey lastPathComponent] stringByDeletingPathExtension];
            videoImage = [[ICMediaManager sharedManager] videoImageWithFileName:[NSString stringWithFormat:@"%@.jpg",name]];//取图片
            if (!videoImage) {
                name = [[[dicMsg objectForKey:@"videoPath"] lastPathComponent] stringByDeletingPathExtension];
                videoImage = [[ICMediaManager sharedManager] videoImageWithFileName:[NSString stringWithFormat:@"%@.jpg",name]];//取图片
            }
        }
    
        // 查看所有图片视频
        [self addSubview:self.closeButton];
        [self bringSubviewToFront:self.closeButton];
        [self bringSubviewToFront:self.illImgBtn];
        [self.closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(48);
            make.left.mas_equalTo(20);
            make.size.mas_equalTo(CGSizeMake(32, 32));
        }];
        
    }
    
    // 进度条、播放、暂停
    self.totalLabel.text = [self obtainPlayTime:self.player.currentItem.asset.duration];
    [self.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(0.1, NSEC_PER_SEC) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        CGFloat progress = CMTimeGetSeconds(weakSelf.player.currentItem.currentTime) / CMTimeGetSeconds(weakSelf.player.currentItem.asset.duration);
        if (!weakSelf.isSlider) {
           weakSelf.slider.value = progress;
        }
        weakSelf.playingTimeLabel.text = [weakSelf obtainPlayTime:time];
//        NSLog(@"%@ === %lf",weakSelf.playingTimeLabel.text,progress);
        if (weakSelf.currentPlayTime < 0.3) {
            weakSelf.currentPlayTime += 0.01;
            if (weakSelf.currentPlayTime >= 0.3) {
                weakSelf.pauseView.hidden = YES;
                weakSelf.playButton.hidden = YES;
                weakSelf.closeButton.hidden = YES;
            }
        }
        if (progress == 1.0) {
            [weakSelf.pauseButton setImage:[UIImage imageNamed:@"video_icon_play"] forState:UIControlStateNormal];
            weakSelf.pauseButton.selected = NO;
        }
    }];
}
- (void)onPlayOrPauseClick:(UIButton *)sender {
    
    if(QATool.isBusy){
        WCIToast.showMsg(@"通话中，请稍后再试");
        return;
    }
    if (self.playBlock) {
        self.playBlock(self);
    }
    self.pauseButton.selected = !self.pauseButton.isSelected;
    if (self.pauseButton.selected) {
        [sender setImage:[UIImage imageNamed:@"video_icon_suspend"] forState:UIControlStateNormal];
        self.playButton.hidden = YES;
        [self playVideo];;
    }else{
        [sender setImage:[UIImage imageNamed:@"video_icon_play"] forState:UIControlStateNormal];
        self.playButton.hidden = NO;
        self.currentPlayTime = 0;
        [self.player pause];
    }

}
// 获取播放时间
- (NSString *)obtainPlayTime:(CMTime)time {
    NSInteger min = 0, second = 0;
    Float64 seconds = CMTimeGetSeconds(time);
    if (seconds > 60.0) {
        min = seconds / 60;
    }
    second = (NSInteger)seconds % 60;
    return [NSString stringWithFormat:@"%.2ld:%.2ld",min, second];
}
// 滑动时候改变当前播放时间
- (void)onValueChangeClick:(UISlider *)sender {
    Float64 seconds = sender.value * CMTimeGetSeconds(self.player.currentItem.asset.duration);
    CMTime time = CMTimeMakeWithSeconds(seconds, NSEC_PER_SEC);
    
    self.pauseView.hidden = NO;
    self.closeButton.hidden = NO;
    [self.player seekToTime:time completionHandler:^(BOOL finished) {
//        NSLog(@"++++++++++++ end +++++++++++++");
    }];
}
- (void)onValueFinishClick:(UISlider *)sender{
    self.isSlider = NO;
    if (self.pauseButton.isSelected) {
        [self playVideo];
    }
}
- (void)sliderStartClick{
    [self.player pause];
    self.isSlider = YES;
}
- (void)playerItemDidPlayToEndTimeNotification:(NSNotification *)sender {
    if (sender.object != self.player.currentItem) {
        return;
    }
    self.currentPlayTime = 0;
    [self.player seekToTime:kCMTimeZero]; // seek to zero
    [self showRePlay];
}

- (void)showRePlay {
    self.playButton.hidden = NO;
    self.pauseView.hidden = NO;
    self.closeButton.hidden = NO;
    self.pauseButton.selected = NO;
    [self.pauseButton setImage:[UIImage imageNamed:@"video_icon_play"] forState:UIControlStateNormal];
    [self bringSubviewToFront:self.slider];
    [self bringSubviewToFront:self.playingTimeLabel];
    [self bringSubviewToFront:self.pauseButton];
    [self bringSubviewToFront:self.pauseView];
    [self bringSubviewToFront:self.illImgBtn];
}

- (void)clickItem:(UIButton *)sender {
    if(QATool.isBusy){
        WCIToast.showMsg(@"通话中，请稍后再试");
        return;
    }
    if (self.playBlock) {
        self.playBlock(self);
    }
    self.playButton.hidden = YES;
    self.pauseButton.selected = YES;
    [self.pauseButton setImage:[UIImage imageNamed:@"video_icon_suspend"] forState:UIControlStateNormal];
    [self playVideo];
}

- (void)playVideo {
    if (!self.otherPlay) {
        self.otherPlay =  [[AVAudioSession sharedInstance] isOtherAudioPlaying];
    }
    if (self.player) {
        [self.player play];
        QAMessage *msg = [QAMessage yy_modelWithDictionary:self.videoInfo];
        if (msg && msg.clearTime > 0) {
            if (msg.clearStart <= 0 && [msg.clearTime integerValue] > 0) {
                msg.clearStart = ServerTime;
                [[QAIMDatabase sharedInstance] updateClearStarWihtMsg:msg];
            }

            [[NSNotificationCenter defaultCenter] postNotificationName:@"timerClearStart" object:self.videoInfo];
        }
    } else {
        [self releasePlayer];
        [self setUpVideoView];
    }

}

- (void)dealloc {
    NSLog(@"%@ dealloc",NSStringFromClass(self.class));
    if (self.otherPlay) {
        [[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
    }

    @try {
        if (self.currentItem.observationInfo) {
            [self.currentItem removeObserver:self forKeyPath:@"status"];
        }
    }
    @catch(NSException *exception) {
        NSLog(@"--%@", exception);
    }

    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self releasePlayer];
    
    
}

- (void)releasePlayer {
    [self.player pause];
    [self.player.currentItem cancelPendingSeeks];
    [self.player.currentItem.asset cancelLoading];
    [self.playerLayer removeFromSuperlayer];
    [self.player replaceCurrentItemWithPlayerItem:nil];
    [self.videoView removeFromSuperview];
    self.player = nil;
    self.currentItem = nil;
    self.playerLayer = nil;
    self.videoView = nil;
    [self.task cancel];
}


#pragma mark - Recall Message

- (void)noti_bothRecallMsg:(NSNotification *)noti {
    WeakSelf(ws);
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *senderID = noti.object;

        if ([weakSelf.messageFrame.message.msgTo isEqualToString:senderID]) {
            [weakSelf stopAndStartPlayer];
            if (weakSelf.dismissBlock) {
                weakSelf.dismissBlock();
            }
        }
    });
}
- (void)recallMsg:(NSNotification *)noti {
    WeakSelf(ws);
    dispatch_async(dispatch_get_main_queue(), ^{
        NSDictionary *dict = noti.object;
        NSInteger notiMsgServerId = [dict[@"serverMsgId"] integerValue];

        if (weakSelf.messageFrame.message.serverMsgId == notiMsgServerId) {
            [weakSelf stopAndStartPlayer];
//            [weakSelf.player pause];
            [MOAlerter alertWithTitle:(@"消息已被撤回") message:nil leftTitle:nil leftAction:nil rightTitle:(@"知道了") rightAction:^(MOAlerter *alerter) {
                if (weakSelf.dismissBlock) {
                    weakSelf.dismissBlock();
                }
            } touchHide:0];
            
        }
    });
}

#pragma mark - 控制视频暂停播放
/** 暂停重置视频 */
- (void)stopAndStartPlayer{
    self.currentPlayTime = 0;
    [self.player seekToTime:kCMTimeZero]; // seek to zero
    [self.player pause];
    [self stopLoadAnimating];
    self.loadView.hidden = YES;
    self.playButton.hidden = NO;
    [self bringSubviewToFront:self.playButton];
    [self bringSubviewToFront:self.illImgBtn];
    self.pauseView.hidden = YES;
    self.closeButton.hidden = YES;
    self.pauseButton.selected = NO;
    [self.pauseButton setImage:[UIImage imageNamed:@"video_icon_play"] forState:UIControlStateNormal];
}
- (void)stopPlayer{
    [self.player pause];
    self.pauseButton.selected = NO;
    [self.pauseButton setImage:[UIImage imageNamed:@"video_icon_play"] forState:UIControlStateNormal];
}
- (void)startPlayer{
    [self playVideo];
    self.pauseButton.selected = YES;
    [self.pauseButton setImage:[UIImage imageNamed:@"video_icon_suspend"] forState:UIControlStateNormal];
}
/** 播放视频 */
- (void)playPlayer{
    if(QATool.isBusy){
        WCIToast.showMsg(@"通话中，请稍后再试");
        return;
    }
    self.playButton.hidden = YES;
    self.pauseButton.selected = YES;
    [self.pauseButton setImage:[UIImage imageNamed:@"video_icon_suspend"] forState:UIControlStateNormal];
    [self playVideo];;
}
#pragma mark - 关闭视频

- (void)onCloseVideoClick {
    if (self.dismissBlock) {
        self.dismissBlock();
    }
}

#pragma mark -
#pragma mark - set, get

- (UIView *)pauseView {
    if (!_pauseView) {
        _pauseView = [[UIView alloc] initWithFrame:CGRectZero];
        _pauseView.layer.cornerRadius = 5;
        _pauseView.userInteractionEnabled = YES;
        _pauseView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleHeight;
        _pauseView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.5];
        _pauseView.hidden = YES;
    }
    return _pauseView;
}
- (UIButton *)closeButton{
    if (!_closeButton) {
        _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeButton addTarget:self action:@selector(onCloseVideoClick) forControlEvents:UIControlEventTouchUpInside];
        _closeButton.hidden = YES;
        [_closeButton setImage:[UIImage imageNamed:@"video_icon_close"] forState:UIControlStateNormal];
    }
    return _closeButton;
}
- (UILabel *)totalLabel {
    if (!_totalLabel) {
        _totalLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _totalLabel.textColor = UIColor.whiteColor;
        _totalLabel.font = [UIFont systemFontOfSize:12];
        _totalLabel.textAlignment = NSTextAlignmentCenter;
        _totalLabel.userInteractionEnabled = NO;
        [self.pauseView addSubview:_totalLabel];
        [_totalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(40, 15));
            make.centerY.equalTo(self.pauseView).offset(0);
            make.right.mas_equalTo(-5);
        }];
    }
    return _totalLabel;
}

- (UISlider *)slider {
    if (!_slider) {
        _slider = [[UISlider alloc] initWithFrame:CGRectZero];
        _slider.minimumTrackTintColor = UIColor.whiteColor;
        _slider.maximumTrackTintColor = UIColor.lightGrayColor;
        
        //监听滑动开始
        [_slider addTarget:self action:@selector(sliderStartClick) forControlEvents:UIControlEventTouchDown];
        [_slider addTarget:self action:@selector(onValueChangeClick:) forControlEvents:UIControlEventValueChanged];
        [_slider addTarget:self action:@selector(onValueFinishClick:) forControlEvents:UIControlEventTouchUpInside];
        [_slider addTarget:self action:@selector(onValueFinishClick:) forControlEvents:UIControlEventTouchUpOutside];
        [_slider addTarget:self action:@selector(onValueFinishClick:) forControlEvents:UIControlEventTouchCancel];
        
        [self.pauseView addSubview:_slider];
        
        [_slider mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(95);
            make.right.mas_equalTo(-55);
            make.height.mas_equalTo(35);
            make.centerY.equalTo(self.pauseView).offset(0);
        }];
        UIImage *tempImage = [UIImage imageNamed:@"video_icon_cursor"];
//        UIImage *tempImage1 = [UIImage reSizeImage:tempImage toSize:CGSizeMake(12, 12)];
        [_slider setThumbImage:tempImage forState:UIControlStateNormal];
//        [_slider setThumbImage:tempImage forState:UIControlStateHighlighted];
    }
    return _slider;
}

- (UILabel *)playingTimeLabel {
    if (!_playingTimeLabel) {
        _playingTimeLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _playingTimeLabel.text = @"00:00";
        _playingTimeLabel.textColor = UIColor.whiteColor;
        _playingTimeLabel.font = [UIFont systemFontOfSize:12];
        _playingTimeLabel.textAlignment = NSTextAlignmentCenter;
        _playingTimeLabel.userInteractionEnabled = NO;
        [self.pauseView addSubview:_playingTimeLabel];
        [_playingTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(40);
            make.size.mas_equalTo(CGSizeMake(40, 15));
            make.centerY.equalTo(self.pauseView).offset(0);
        }];
    }
    return _playingTimeLabel;
}

- (MOClickRectExpandButton *)pauseButton {
    if (!_pauseButton) {
        _pauseButton = [MOClickRectExpandButton buttonWithType:UIButtonTypeCustom];
        [_pauseButton setImage:[UIImage imageNamed:@"video_icon_suspend"] forState:UIControlStateNormal];
        [_pauseButton addTarget:self action:@selector(onPlayOrPauseClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.pauseView addSubview:_pauseButton];
        [_pauseButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(10);
            make.size.mas_equalTo(CGSizeMake(20, 20));
            make.centerY.equalTo(self.pauseView).offset(0);
        }];
    }
    return _pauseButton;
}

- (UIButton *)playButton {
    if (!_playButton) {
        _playButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playButton setBackgroundImage:[UIImage imageNamed:@"icon_videoplay"] forState:UIControlStateNormal];
        _playButton.hidden = YES;
        [_playButton addTarget:self action:@selector(clickItem:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_playButton];
        [_playButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(60, 60));
            make.centerY.equalTo(self).offset(0);
            make.centerX.equalTo(self).offset(-25);
        }];
    }
    return _playButton;
}

- (UIImageView *)loadView {
    if (!_loadView) {
        _loadView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"video_icon_loading"]];
        [self addSubview:_loadView];
        [self bringSubviewToFront:_loadView];
        [self bringSubviewToFront:self.illImgBtn];
        CABasicAnimation * tfBA = [CABasicAnimation animation];
        tfBA.keyPath = @"transform.rotation.z";
        tfBA.duration = 1;
        tfBA.removedOnCompletion = NO;
        tfBA.fillMode = kCAFillModeForwards;
        tfBA.byValue = @(M_PI *2);
        tfBA.repeatCount = MAXFLOAT;
        [_loadView.layer addAnimation:tfBA forKey:@"tr"];
        
        [_loadView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.mas_centerX).offset(-25);
            make.centerY.equalTo(self.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(26, 26));
        }];
    }
    return _loadView;
}

- (void)startLoadAnimating {
    [self.loadView.layer removeAllAnimations];
    [self bringSubviewToFront:self.loadView];
    [self bringSubviewToFront:self.illImgBtn];
    CABasicAnimation * tfBA = [CABasicAnimation animation];
    tfBA.keyPath = @"transform.rotation.z";
    tfBA.duration = 1;
    tfBA.removedOnCompletion = NO;
    tfBA.fillMode = kCAFillModeForwards;
    tfBA.byValue = @(M_PI *2);
    tfBA.repeatCount = MAXFLOAT;
    [self.loadView.layer addAnimation:tfBA forKey:@"tr"];
}
- (UIButton *)illImgBtn{
    if (!_illImgBtn) {
        _illImgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _illImgBtn.backgroundColor = UIColor.blackColor;
        _illImgBtn.hidden = YES;
        [_illImgBtn setImage:[UIImage imageNamed:@"album_ill_vid"] forState:UIControlStateNormal];
    }
    return _illImgBtn;
}
- (void)stopLoadAnimating {
    [self.loadView.layer removeAllAnimations];
}

@end
